package com.ld.security.common.mybatis.util;

import com.ld.security.common.core.util.ReflectionUtil;

import java.util.Arrays;
import java.util.List;

public class TableUtil {

    private static boolean eq(Object x,Object y,List<String> fields){
        for (String fieldName : fields) {
            Object xv = ReflectionUtil.invokeGetter(x, fieldName);
            Object yv = ReflectionUtil.invokeGetter(y, fieldName);
            if(!xv.equals(yv)){
                return false;
            }
        }
        return true;
    }

  /**
   * 聚合行,n2复杂度
   *
   * @param list
   * @param fieldNames
   * @return
   */
  public static List<GroupColumn> groupRows(List<?> list, List<String> fieldNames) {

    GroupColumn[] columns = new GroupColumn[list.size()];

    for (int x = 0; x < list.size(); x++) {
      Object xo = list.get(x);

      GroupColumn column = columns[x];
      if (column == null) {
        column = new GroupColumn();
        columns[x] = column;
      } else {
        continue;
      }

      for (int y = x + 1; y < list.size(); y++) {
          Object yo = list.get(y);


        boolean b  =   eq(xo,yo,fieldNames);

        if (b) {
          GroupColumn next = column.incrRowspan();
          columns[y] = next;
        }else {
            break;
        }
      }
    }
    return Arrays.asList(columns);
  }

  public static List<GroupColumn> groupRows(List<?> list, String... fieldNames) {
    return groupRows(list,Arrays.asList(fieldNames));
  }
}
